<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        class Mypromise {
            constructor(fn) {
                this.state = 'pending' // promise进行中的状态
                this.value = null
                let resolve = (val) => {
                    // console.log('这是resolve');
                    if (this.state === 'pending') {
                        this.state = 'fullfilled' // promise成功的状态
                        this.value = val
                    }
                }

                let reject = (val) => {
                    // console.log('这是reject');
                    if (this.state === 'pending') {
                        this.state = 'rejected' // promise失败的状态
                        this.value = val
                    }
                }

                // try尝试的意思 
                try {
                    fn(resolve, reject) // 如果用户传入的不是一个函数 则函数执行会报错
                } catch (err) { // try尝试产生的错误会进入catch
                    // console.log('promise需要接收一个函数')
                    throw new Error('promise需要接收一个函数')
                }
            }


            then(success, faild) {
                if (this.state === 'fullfilled') {
                    success(this.value)
                } else if (this.state === 'rejected') {
                    faild(this.value)
                }
            }
        }






        let promise = new Mypromise(function(res, rej) {
            // res(123)
            rej(234)
        })

        promise.then(success => {
            console.log(success);
        }, err => {
            console.log(err);
        })
    </script>
</body>

</html>